package com.spatio.serving.basic.service.template.core.component.service.impl;

import com.spatio.serving.basic.service.template.common.constant.CacheConstants;
import com.spatio.serving.basic.service.template.common.domain.UserInfoDo;
import com.spatio.serving.basic.service.template.common.domain.UserLoginDo;
import com.spatio.serving.basic.service.template.common.util.*;
import com.spatio.serving.basic.service.template.core.component.invoker.IdGenInvoker;
import com.spatio.serving.basic.service.template.core.component.service.UserService;

import com.spatio.serving.basic.service.template.mysql.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    private static final String KEY = CacheConstants.CALORIES_CODE_KEY_PREFIX;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private IdGenInvoker idGenInvoker;
    @Autowired
    private UserService userService;


    //bondee邮箱发送验证码功能
//    @Autowired
//    private cMidUserInvoker midUserInvoker;
//    String email="2712543529@qq.com";

    private SendSms sendSms;



    @Override
    public UserLoginDo sendCode(UserLoginDo user) throws Exception {
        String phone = user.getPhone_number();
        //1.验证手机号是否符合规范
        if (!RegexUtils.isValidPhone(phone)) {
            user.setCode("手机格式不正确");
            return user;
        }
        //midUserInvoker.sendEmailCode(email,);

        boolean isExist = userMapper.checkPhoneNumberExists(phone);
        if(isExist){
            BigInteger user_id=userMapper.checkUserExist(phone);
            user.setUser_id(user_id);

            //2.符合，生成验证码（有字母）
            String code = ValidateCodeutils.generateValidateCode4String(6);
            user.setCode(code);
            //sendSms.sendSms(phone,code);
            redisTemplate.opsForValue().set(KEY+phone,code,5, TimeUnit.MINUTES);
            return user;
        }else {
            BigInteger user_id = new BigInteger(idGenInvoker.getIdGenValue());
            userMapper.insertPhoneNumber(user_id,phone);

            System.out.println("插入完成");
            String code = ValidateCodeutils.generateValidateCode4String(6);
            user.setCode(code);
            user.setUser_id(user_id);
            //sendSms.sendSms(phone,code);
            redisTemplate.opsForValue().set(KEY+phone,code,5, TimeUnit.MINUTES);
            return user;
        }

    }

    @Override
    public String login(UserLoginDo user) {
        String phone = user.getPhone_number();
        String code=user.getCode();

        if (!RegexUtils.isValidPhone(phone)) {
            return "手机号格式不正确，请重新输入";
        }
        String cache_code = (String) redisTemplate.opsForValue().get(KEY+phone);
        if(cache_code.equals(code)){
            HashMap<String,String> payload = new HashMap<>();
            BigInteger user_id=userService.getLoginInfo(phone).getUser_id();
            payload.put("user_id",String.valueOf(user_id));
            String token = JwtUtils.getToken(payload);
            return token;
        }
        else{
            return "登陆失败";
        }
    }

    @Override
    public boolean update(UserInfoDo user) {
        UserInfoDo currentUser = userMapper.findById(user.getUser_id());
        if (currentUser != null &&
                    Objects.equals(currentUser.getHeight(), user.getHeight()) &&
                    Objects.equals(currentUser.getWeight(), user.getWeight()) &&
                    Objects.equals(currentUser.getGender(), user.getGender()) &&
                    Objects.equals(currentUser.getAge(), user.getAge()) &&
                    Objects.equals(currentUser.getWater_fre(), user.getWater_fre()) &&
                    Objects.equals(currentUser.getExercise_fre(), user.getExercise_fre()) &&
                    Objects.equals(currentUser.getTarget_weight(), user.getTarget_weight()) &&
                    Objects.equals(currentUser.getChange_per_week(), user.getChange_per_week())
//                    Objects.equals(currentUser.getTarget_calories(), user.getTarget_calories()) &&
//                    Objects.equals(currentUser.getTarget_proteins(), user.getTarget_proteins()) &&
//                    Objects.equals(currentUser.getTarget_carbs(), user.getTarget_carbs()) &&
//                    Objects.equals(currentUser.getTarget_fats(), user.getTarget_fats())

        )
        {
                // 如果数据没有变化，不执行更新操作
                return true;
        }
        user= ComputeCaUtils.recomStatics(user);
        boolean flag = userMapper.update(user);
        return flag;
    }




//    @Override
//    public boolean update(UserInfoDo user) {


//        UserInfoDo currentUser = userMapper.findByPhoneNumber("1000");
//        if (currentUser != null &&
//                    Objects.equals(currentUser.getHeight(), user.getHeight()) &&
//                    Objects.equals(currentUser.getWeight(), user.getWeight()) &&
//                    Objects.equals(currentUser.getGender(), user.getGender()) &&
//                    Objects.equals(currentUser.getAge(), user.getAge())) {
//                // 如果数据没有变化，不执行更新操作
//                return true;
//        }
//        boolean flag = userMapper.update(user);
//        return true;
//    }

    @Override
    public UserInfoDo getUserInfo(UserInfoDo user) {

        BigInteger user_id=user.getUser_id();
        //UserLoginDo currentUser = userMapper.findByPhoneNumber(phone);
        UserInfoDo currentUser = userMapper.findById(user_id);
        return currentUser;
    }

    @Override
    public UserLoginDo getLoginInfo(String phone) {
        UserLoginDo loginUser = userMapper.findByPhoneNumber(phone);
        return loginUser;
    }


}

